package com.homestay.dao.impl;

import com.homestay.beans.Home;
import com.homestay.dao.HomeDao;
import com.homestay.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class HomeDaoImpl implements HomeDao {

    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());

    @Override
    public List<Home> query(String h_type, String state, String num) {
        try {
            String sql = "select * from tb_home where h_type like ? and state like ? and num like ?";
            return qr.query(sql, new BeanListHandler<>(Home.class), "%" + h_type + "%", "%" + state + "%", "%" + num + "%");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int add(Home home) {
        try {
            return qr.update("insert into tb_home values(null,?,?,?,?,?,?,now(),now())", home.getNum(), home.getH_type(), home.getPrice(), home.getState(), home.getImg(), home.getText());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteById(String id) {
        try {
            return qr.update("delete from tb_home where id = ?", id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Home queryById(String id) {
        try {
            return qr.query("select * from tb_home where id = ?", new BeanHandler<>(Home.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Home home) {
        try {
            return qr.update("update tb_home set num = ?, h_type = ?, price = ?, state = ?, img = ?, text = ?, updateTime = now() where id = ?",
                    home.getNum(), home.getH_type(), home.getPrice(), home.getState(), home.getImg(), home.getText(), home.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Home> queryByNum(int homeNum) {
        String sql = "select * from tb_home where num = ?";
        try {
            return qr.query(sql, new BeanListHandler<>(Home.class), homeNum);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateStateById(String homeId,String state) {
        try {
            return qr.update("update tb_home set state = ? where id = ?", state, homeId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
